package com.zimin.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 切面工具类
 * @author zimin
 * @since 2021/11/15 5:47 下午
 */
@Slf4j
public class AopUtils extends org.springframework.aop.support.AopUtils {

    /**
     * <p>获取被切的方法</p>
     *
     * @param joinPoint 切点
     * @return java.lang.reflect.Method
     * @since 2022-05-24 10:10:40
     */
    public static Method getMethod(ProceedingJoinPoint joinPoint) {
        var signature = joinPoint.getSignature();
        if (!(signature instanceof MethodSignature)) {
            log.error("不支持的类型，{}，期望MethodSignature，发现：{}", joinPoint.getTarget().getClass().getName(), signature.toShortString());
            return null;
        } else {
            var methodSignature = (MethodSignature) signature;
            return methodSignature.getMethod();
        }
    }
    /**
     * <p>获取切点上的方法</p>
     *
     * @param joinPoint 切点
     * @param vClass 注解类型
     * @return V
     * @since 2022-05-24 10:11:30
     */
    public static <V extends Annotation> V getAnnotation(ProceedingJoinPoint joinPoint, Class<V> vClass) throws NoSuchMethodException {
        var method = getMethod(joinPoint);
        if (method != null) {
            var target = joinPoint.getTarget();
            var interfaces = target.getClass().getInterfaces();
            if (ObjectUtils.isEmpty(interfaces)) {
                return null;
            }
            return interfaces[0].getMethod(method.getName(),
                    method.getParameterTypes()).getAnnotation(vClass);
        }
        return null;
    }

}
